package common

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
)

const (
	ApiUrl = "https://api.kdzl.cn"
	/*
		appId,appSecret,did 需要根据你自己的公司情况替换为相关公司的
	*/
	/*AppId = 70886
	AppSecret = "a29cd13751c544f3"
	Did = 1176098*/
	AppId = 65540
	AppSecret = "12345"
	Did = 10000
	TokenExpire = 3600
)


func ToInt32Ptr(i int32) *int32 {
	v := i
	return &v
}
func ToInt64tr(i int64) *int64 {
	v := i
	return &v
}

func HttpGetData(url string, v interface{}) error {
	rsp, err := http.Get(url)
	if err != nil {
		return errors.New(fmt.Sprintf("Get %s from server, http error = %v", url, err))
	}
	defer rsp.Body.Close()
	if rsp.StatusCode != 200 {
		return errors.New(fmt.Sprintf("Get %s server, http response status not 200, StatusCode=%v", url, rsp.StatusCode))
	}

	rspBody, err := ioutil.ReadAll(rsp.Body)
	if err != nil {
		return  errors.New(fmt.Sprintf("Get %s server, read http rsp body failed! err=%v", url, err))
	}
	fmt.Println(string(rspBody))
	err = json.Unmarshal(rspBody, v)
	if err != nil {
		return errors.New(fmt.Sprintf("Get %s server, umarshal body failed! err=%v", url, err))
	}
	return nil
}

func HttpPostData(url string, req interface{}, v interface{}) error {
	body,_ := json.Marshal(req)
	fmt.Println(string(body))
	rsp, err := http.Post(url, "application/x-www-form-urlencoded", bytes.NewReader(body))
	if err != nil {
		return errors.New(fmt.Sprintf("Get %s from server, http error = %v", url, err))
	}
	defer rsp.Body.Close()
	if rsp.StatusCode != 200 {
		return errors.New(fmt.Sprintf("Get %s server, http response status not 200, StatusCode=%v", url, rsp.StatusCode))
	}

	rspBody, err := ioutil.ReadAll(rsp.Body)
	if err != nil {
		return  errors.New(fmt.Sprintf("Get %s server, read http rsp body failed! err=%v", url, err))
	}
	fmt.Println(string(rspBody))
	err = json.Unmarshal(rspBody, v)
	if err != nil {
		return errors.New(fmt.Sprintf("Get %s server, umarshal body failed! err=%v", url, err))
	}
	return nil
}